//
//  SSPublishViewController.swift
//  weibo
//
//  Created by 邵帅 on 16/6/30.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit

let myHolderString = "听说篮球场和美女更配哦"
class SSPublishViewController: UIViewController {
    
    
    override func viewWillDisappear(animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
        setupTextView()
        setupToolBar()
        
        // 监听键盘的通知
        // UIKeyboardDidChangeFrameNotification -- 已经改变
        // UIKeyboardWillChangeFrameNotification -- 将要改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SSPublishViewController.changeNotification(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 监听表情点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SSPublishViewController.insertEmoticon(_:)), name: kNotificationShowEmoticon, object: nil)
        
        // 监听删除按钮
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SSPublishViewController.deleteEmoticon(_:)), name: kNotificationDeleteEmoticon, object: nil)
    }
    
    // 标题栏
    func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(SSPublishViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: #selector(SSPublishViewController.publishClick))
        
        let myTitleView = UILabel(frame: CGRectMake(0,0,200,44))
        
        myTitleView.text = "叶良辰\n 赵日天"
        myTitleView.textAlignment = .Center
        myTitleView.numberOfLines = 0
        
        // 文字属性
        let attribute = NSMutableAttributedString(string: myTitleView.text!)
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16),NSForegroundColorAttributeName: UIColor.redColor()], range: NSMakeRange(0, 3))
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName: UIColor.blueColor()], range: NSMakeRange(3, 5))
        
        myTitleView.attributedText = attribute
        
        navigationItem.titleView = myTitleView
    }
    
    func cancelClick() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    // 发布微博
    func publishClick() {
        
        if chooseView.getImage().count > 0 {
            publishPic()
        }else {
        publishText()
        }
    }
    
    func publishText() {
        
        guard let access_token = SSOauthModel.shareInstance.access_token else {
            
            return
        }
        
        guard let publishString = textView.setPublishTextString() else {
            return
        }
        
        let param = ["access_token": access_token,
                     "status": publishString
        ]
        print(param)
        
        SSHTTPClient.shareInstance.request(.POST, URLString: "https://api.weibo.com/2/statuses/update.json", parameters: param, progress: nil, success: { (_, JSON) in
            
            print("发布成功")
            
        }) { (_, error) in
            
            print(error)
        }
        
    }
    
    func publishPic() {
        
        guard let access_token = SSOauthModel.shareInstance.access_token else {
            
            return
        }
        
        guard let publishString = textView.setPublishTextString() else {
            return
        }
        
        let param = ["access_token": access_token,
                     "status": publishString
        ]
        
        let image = chooseView.getImage().first!
        
        let data = UIImageJPEGRepresentation(image, 0.4)
        
        SSHTTPClient.shareInstance.POST("https://upload.api.weibo.com/2/statuses/upload.json", parameters: param, constructingBodyWithBlock: { (formdata) in
            
            formdata.appendPartWithFileData(data!, name: "pic", fileName: "aa.png", mimeType: "image/jpeg")
            
            
            
            }, progress: nil, success: { (_, JSON) in
                
                printLog("发布成功")
            }) { (_, error) in
                printLog(error)
        }
        
        
    }
    
    
    // 输入框
    func setupTextView() {

        textView.frame = view.bounds
        textView.holderString = myHolderString
        textView.font = UIFont.systemFontOfSize(16)
        textView.backgroundColor = UIColor.orangeColor()
        
        self.view.addSubview(textView)
        
        textView.delegate = self
        
        //可以让它垂直拖拽 --
        textView.keyboardDismissMode = .OnDrag
        //拖拽的时候，键盘消失
        textView.alwaysBounceVertical = true
        
        textView.addSubview(chooseView)
        chooseView.snp_makeConstraints { (make) in
            
            make.left.equalTo(self.view).offset(10)
            make.top.equalTo(self.view).offset(200)
            make.height.width.equalTo(UIScreen.mainScreen().bounds.width - 20)
        }
        
    }
    
    // 底部toolBar
    func setupToolBar() {
        
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor.darkGrayColor()
        toolBar.snp_makeConstraints { (make) in
            
            make.height.equalTo(44)
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view.snp_bottom)
        }
        
        // 我们可以把一些固定的东西按照数据源的形式,展示
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
                            ["imageName": "compose_addbutton_background"]]
        
        // 定义一个数组，存储item
        var items = [UIBarButtonItem]()
        
        
        for itemSet in itemSettings {
            
            let btn = UIButton(type: UIButtonType.Custom)
            
            btn.setImage(UIImage(named: itemSet["imageName"]!), forState: .Normal)
            
            // 点击方法
            let action = itemSet["action"]
            
            if let Oaction = action {
                
                btn.addTarget(self, action: Selector(Oaction), forControlEvents: .TouchUpInside)
            }
            
            btn.sizeToFit()
            
            let item = UIBarButtonItem(customView: btn)
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
    
    
    
    
    // 懒加载
    private lazy var textView: SSHolderTextView = SSHolderTextView()
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var chooseView: SSChooseView = {
        
        let chooseView = SSChooseView()
        
        chooseView.closure = {[weak self]()->() in
            
            self!.choosePicture()
        }
        
        
        return chooseView
    }()
    
    // 表情键盘
    private lazy var emoticonView: SSEmoticonView = {
        
        let emoticon = SSEmoticonView(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.size.width,216))
        
        return emoticon
    }()
}


extension SSPublishViewController {
    
    // 键盘移动通知
    @objc private func changeNotification(noti: NSNotification){
        
        let rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        if rect.origin.y == UIScreen.mainScreen().bounds.height {
            
            toolBar.snp_updateConstraints(closure: { (make) in
                
                make.bottom.equalTo(self.view.snp_bottom)
            })
        }else {
            
            toolBar.snp_updateConstraints(closure: { (make) in
                
                make.bottom.equalTo(self.view.snp_bottom).offset(-rect.size.height)
            })
        }
        
        // 约束动画
        UIView.animateWithDuration(0.25) { 
            
            self.toolBar.layoutIfNeeded()
        }
    }
    
    
    // 显示表情的通知
    @objc private func insertEmoticon(noti: NSNotification){
        
        if let userInfo = noti.userInfo {
            
            let emoticon = userInfo["emoticon"] as? SSEmoticon
            
            if let Oemoticon = emoticon {
                
                textView.insertEmoticon(Oemoticon)
                
            }
        }
     
    }
    
    
    // 删除通知
    @objc private func deleteEmoticon(noti: NSNotification){
        
        textView.deleteBackward()
    }
}


// tooBar点击代理
extension SSPublishViewController {
    
    // 选择图片
    func choosePicture() {
        
        if chooseView.isMoreThanNine() {
            
            return
        }
        
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            
            let imagePicker = UIImagePickerController()
            
            imagePicker.sourceType = .PhotoLibrary
            
            imagePicker.delegate = self
            
            presentViewController(imagePicker, animated: true, completion: nil)
        }
        
    }
    
    // 添加表情
    func inputEmoticon() {
        
        if textView.inputView == nil {
            
            textView.inputView = emoticonView
        }else {
            
            textView.inputView = nil
        }
        
        textView.reloadInputViews()
        textView.becomeFirstResponder()
    }
    
}

// 图片选择代理
extension SSPublishViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        chooseView.addImage(image)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}



// 输入文字代理
extension SSPublishViewController: UITextViewDelegate {
    
    
    func textViewDidChange(textView: UITextView) {
        
        if self.textView.hasText() {
            
            self.textView.holderString = ""
        }else {
            
            self.textView.holderString = myHolderString
        }
        
        self.textView.setNeedsDisplay()
    }
 
}
